#include "Tangram.h"
#include <iostream>
#include <fstream>
#include <sstream>

namespace qtangram {
bool Tangram::loadTangramFromFile(QString path) {
    ready=false;
    tans.clear();
    Tan tan;
    std::ifstream f;
    std::string line;
    std::stringstream ss;

    f.open(path.toAscii());
    if (!f.is_open()) return false;

    unsigned int id;
    double x,y;
    int i, crgb[3];
    QPointF pt;
    while(f.good())
    {
        tan.getOriginalPoly().clear();
        tan.getCurrentPoly().clear();
        std::getline(f,line);
        ss.str(line);

        ss >> id;
        ss >> x;
        ss >> y;

        tan.ID = id;
        tan.getReferencePoint().setX(x);
        tan.getReferencePoint().setY(y);
        tan.currentPoint.setX(x);
        tan.currentPoint.setY(y);
        for (i=0; i<3; ++i)
        {
            ss >> crgb[i];
            if (crgb[i]<0 || crgb[i]>255) crgb[i]=0;
        }
        tan.getBackgroundColor().setRed(crgb[0]);
        tan.getBackgroundColor().setGreen(crgb[1]);
        tan.getBackgroundColor().setBlue(crgb[2]);

        while(ss.good())
        {
            ss >> x;
            if(ss.good())
            {
                ss >> y;
                pt.setX(x+tan.getReferencePoint().x());
                pt.setY(y+tan.getReferencePoint().y());
                tan.getOriginalPoly().push_back(pt);
                tan.getCurrentPoly().push_back(pt);
            }
        }

        tan.recalculateCurrentPolygon();

        ss.clear();

        if (tan.getLength()>2)
        {
            tans.push_back(tan);
        }
    }

    if (tans.size()>2) ready=true;
    return ready;
}
}
